package com.jason.config;

import org.apache.commons.collections.CollectionUtils;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.Args;

import java.io.IOException;
import java.util.Objects;
import java.util.Set;

/**
 * @author he peng
 * @create 2018/1/9 22:58
 * @see
 */
public class  WilddogApiHttpRequestRetryHandler extends DefaultHttpRequestRetryHandler {

    private final Set<Class<? extends IOException>> allowRetriableClasses;

    public WilddogApiHttpRequestRetryHandler(int retryCount, boolean requestSentRetryEnabled, Set<Class<? extends IOException>> allowRetriableClasses) {
        super(retryCount , requestSentRetryEnabled);
        if (CollectionUtils.sizeIsEmpty(allowRetriableClasses)) {
            throw new IllegalArgumentException("allowRetriableClasses must not be empty");
        }
        this.allowRetriableClasses = allowRetriableClasses;
    }

    @Override
    public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
        Args.notNull(exception, "Exception parameter");
        Args.notNull(context, "HTTP context");
        if (executionCount > getRetryCount()) {
            // Do not retry if over max retry count
            return false;
        }
        Throwable causeException = Objects.nonNull(exception.getCause()) ? exception.getCause() : exception;
        if (this.allowRetriableClasses.contains(causeException.getClass())) {
            return true;
        } else {
            return super.retryRequest(exception , executionCount , context);
        }
    }

    public Set<Class<? extends IOException>> getAllowRetriableClasses() {
        return allowRetriableClasses;
    }
}
